package com.nodecollege.cloud.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nodecollege.cloud.common.constants.NCConstants;
import com.nodecollege.cloud.common.model.NCResult;
import com.nodecollege.cloud.common.model.QueryVO;
import com.nodecollege.cloud.common.model.po.UpmsApi;
import com.nodecollege.cloud.common.model.po.UpmsApiVisit;
import com.nodecollege.cloud.common.model.po.UpmsTenant;
import com.nodecollege.cloud.common.model.vo.ApiVisitQuery;
import com.nodecollege.cloud.common.model.vo.ApiVisitVO;
import com.nodecollege.cloud.common.utils.DateUtils;
import com.nodecollege.cloud.common.utils.NCUtils;
import com.nodecollege.cloud.common.utils.RedisLock;
import com.nodecollege.cloud.common.utils.RedisUtils;
import com.nodecollege.cloud.dao.mapper.UpmsApiVisitMapper;
import com.nodecollege.cloud.dao.mapper.UpmsTenantMapper;
import com.nodecollege.cloud.service.ApiService;
import com.nodecollege.cloud.service.ApiVisitService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 接口访问
 *
 * @author LC
 * @date 2019/12/23 15:26
 */
@Service
public class ApiVisitServiceImpl implements ApiVisitService {

    private static final Logger logger = LoggerFactory.getLogger(ApiVisitServiceImpl.class);

    private static final String UPMS_API_VISIT = "upms:apiVisit:";

    @Autowired
    private ApiService apiService;

    @Autowired
    private UpmsTenantMapper upmsTenantMapper;

    @Autowired
    private UpmsApiVisitMapper upmsApiVisitMapper;

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisLock redisLock;

    /**
     * 查询接口访问列表
     *
     * @param apiVisitQuery
     * @return
     */
    @Override
    public NCResult<ApiVisitVO> getApiVisitList(ApiVisitQuery apiVisitQuery) {
        List<UpmsApiVisit> list = new ArrayList<>();
        Long total = 0L;
        if (NCConstants.INT_NEGATIVE_1.equals(apiVisitQuery.getPageSize())) {
            list = upmsApiVisitMapper.selectApiVisitList(apiVisitQuery);
            total = NCUtils.isNullOrEmpty(list) ? 0 : Long.parseLong(list.size() + "");
        } else {
            Page page = PageHelper.startPage(apiVisitQuery.getPageNum(), apiVisitQuery.getPageSize());
            if (apiVisitQuery.isSort()) {
                page.setOrderBy(apiVisitQuery.getSortKey() + " " + apiVisitQuery.getSortDirection());
            }
            list = upmsApiVisitMapper.selectApiVisitList(apiVisitQuery);
            total = page.getTotal();
        }
        List<UpmsApi> apiList = apiService.getApiListCache();
        for (int j = 0; j < list.size(); j++) {
            for (int i = 0; i < apiList.size(); i++) {
                if (apiList.get(i).getApiId().equals(list.get(j).getApiId())) {
                    list.get(j).setApplicationName(apiList.get(i).getApplicationName());
                    list.get(j).setControllerName(apiList.get(i).getControllerName());
                    list.get(j).setModularName(apiList.get(i).getModularName());
                    list.get(j).setDescription(apiList.get(i).getDescription());
                    list.get(j).setApiUrl(apiList.get(i).getApiUrl());
                }
            }
        }
        List<UpmsTenant> tenantList = upmsTenantMapper.selectTenantListByMap(new QueryVO<>().toMap());
        List<ApiVisitVO> voList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ApiVisitVO apiVisitVO = new ApiVisitVO();
            BeanUtils.copyProperties(list.get(i), apiVisitVO);
            voList.add(apiVisitVO);
        }
        for (int j = 0; j < voList.size(); j++) {
            for (int i = 0; i < tenantList.size(); i++) {
                if (tenantList.get(i).getTenantId().equals(voList.get(j).getTenantId())) {
                    voList.get(j).setTenantName(tenantList.get(i).getTenantName());
                }
            }
        }

        return NCResult.ok(voList, total);
    }

    /**
     * 添加接口访问记录到redis中
     *
     * @param upmsApiVisit
     */
    @Override
    public void addApiVisitCache(UpmsApiVisit upmsApiVisit) {
        logger.debug("接口访问记录 {}", JSONObject.toJSONString(upmsApiVisit));
        // 1. 查出接口id
        List<UpmsApi> apiList = apiService.getApiListCache();
        for (int i = 0; i < apiList.size(); i++) {
            if (apiList.get(i).getApplicationName().equals(upmsApiVisit.getApplicationName())
                    && apiList.get(i).getControllerName().equals(upmsApiVisit.getControllerName())
                    && apiList.get(i).getApiUrl().equals(upmsApiVisit.getApiUrl())) {
                // 设置接口id
                upmsApiVisit.setApiId(apiList.get(i).getApiId());
                break;
            }
        }
        String dateH = DateUtils.formatDate(new Date(), DateUtils.DATE_PATTERN.YEAR_HOUR_FORMAT);
        String key = UPMS_API_VISIT + dateH + ":" + upmsApiVisit.getApiId() + ":" + upmsApiVisit.getTenantId()
                + ":" + upmsApiVisit.getAccessSource()+ ":-" + upmsApiVisit.getRequestIp();

        redisUtils.increment(key, 1);
        logger.debug("{} 访问量 {}", key, redisUtils.get(key, Long.class));
        logger.debug("所有的key {}", redisUtils.keys(UPMS_API_VISIT + dateH + ":*"));
    }

    /**
     * 添加接口访问记录
     *
     * @param apiVisitList
     */
    @Override
    public void addApiVisitList(List<UpmsApiVisit> apiVisitList) {
        for (int i = 0; i < apiVisitList.size(); i++) {
            upmsApiVisitMapper.insert(apiVisitList.get(i));
        }
    }

    /**
     * 每小时第一分钟的时候将redis中的数据保存到数据库中，同时清空redis
     */
    @Scheduled(cron = "0 1 0/1 * * ? ")
    public void sync() {
        logger.info("定时任务！！！！");
        Calendar now = Calendar.getInstance();
        now.setTime(new Date());
        now.add(Calendar.HOUR, -1);
        String dateH = DateUtils.formatDate(now.getTime(), DateUtils.DATE_PATTERN.YEAR_HOUR_FORMAT);
        logger.info("上一个小时的时间{}", dateH);
        try {
            if (redisLock.tryLock(dateH, NCConstants.LONG_30)) {
                List<UpmsApiVisit> list = getApiVisitListByDateH(dateH);
                for (int i = 0; i < list.size(); i++) {
                    upmsApiVisitMapper.insert(list.get(i));
                }
                redisUtils.delete(redisUtils.keys(UPMS_API_VISIT + dateH + ":*"));
            }
        } catch (Exception e) {
            logger.error("定时保存接口访问记录任务执行出错！！！", e);
        } finally {
            redisLock.releaseLock(dateH, NCConstants.LONG_30);
        }
    }

    /**
     * 从redis中获取指定时间段的访问数据
     *
     * @param dateH
     * @return
     */
    private List<UpmsApiVisit> getApiVisitListByDateH(String dateH) {
        String key = UPMS_API_VISIT + dateH + ":*";
        List<UpmsApiVisit> list = new ArrayList<>();
        List<String> allKeys = new ArrayList<>(redisUtils.keys(key));
        for (int i = 0; i < allKeys.size(); i++) {
            String[] args = allKeys.get(i).split(":");
            if (args.length >= 5) {
                String date = args[2].substring(0, 8);
                String hh = args[2].substring(8);
                UpmsApiVisit visit = new UpmsApiVisit();
                visit.setVisitDate(date);
                visit.setVisitH(hh);
                visit.setApiId(Long.valueOf(args[3]));
                visit.setTenantId(NCConstants.NULL_STRING.equalsIgnoreCase(args[4]) ? null : Long.valueOf(args[4]));
                visit.setAccessSource(args[5]);
                visit.setRequestIp(allKeys.get(i).substring(allKeys.get(i).lastIndexOf("-") + 1));
                visit.setVisitCount(redisUtils.get(allKeys.get(i), Long.class));
                list.add(visit);
            }
        }
        logger.debug("{} 时间段的访问数据 {}", dateH, JSONObject.toJSONString(list));
        return list;
    }
}
